<?php
namespace App\Controllers;

use App\Lib\Db;
use App\Lib\View;

class TestController
{
    /**
     * @var Db
     */
    private $db;

    public function __construct()
    {
        $this->db = new Db();
    }

    public function index()
    {
        // 每页显示的数据数目
        $pageSize = 5;

        // 总页数
        $pageCount = $this->db
            ->query('select ceil(count(*)/?) as c from messages', [$pageSize])[0]
            ->c;

        // 当前页码
        $pn = isset($_GET['pn']) ? $_GET['pn'] : 1;

        // 分页查询数据
        $offset = ($pn - 1) * $pageSize;
        $sql = "select * from messages order by created_at desc limit $offset, $pageSize";
        $messages = $this->db->query($sql);

        $view = new View('index', [
            'pn' => $pn,
            'pageCount' => $pageCount,
            'messages' => $messages
        ]);
        return $view;
    }
}